package strings;

import java.util.HashMap;
import java.util.Map;

public class IntToRoman {
    public String intToRoman(int num){
        if(num <= 0 || num > 3999){
            return "";
        }
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "I");
        map.put(4, "IV");
        map.put(5, "V");
        map.put(9, "IX");
        map.put(10, "X");
        map.put(40, "IL");
        map.put(50, "L");
        map.put(90, "XC");
        map.put(100, "C");
        map.put(400, "CD");
        map.put(500, "D");
        map.put(900, "CM");
        map.put(1000, "M");
        int level = 1;
        StringBuilder res = new StringBuilder();
        while(num > 0){
            int cur = num % (level * 10);
            int count = cur / level;
            StringBuilder sb = new StringBuilder();
            if(count >= 5 && count <=8){
                String five = map.get(5 * level);
                sb.append(five);
                count = count -5;
            }
            if(count >= 1 && count <= 3){
                String base = map.get(level);
                for(int i = 0; i < count; i ++){
                    sb.append(base);
                }
            } else if( count == 4){
                sb.append(map.get(4*level));
            } else if(count == 9){
                sb.append(map.get(9*level));
            }
            num = num - cur;
            level *= 10;
            res.insert(0, sb);
        }
        return res.toString();
    }
}
